package com.yxinmiracle.filter;

import com.yxinmiracle.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @version 1.0
 * @author： YxinMiracle
 * @date： 2021-08-15 20:23
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    //令牌头名字
    private static final String AUTHORIZE_TOKEN = "Authorization";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 先获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 2. 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 3. 判断如果是登录的路径 放行
        String path = request.getURI().getPath();
        if (path.startsWith("/api/user/login")){
            return chain.filter(exchange); // 放行
        }
        // 4. 从请求参数/请求头/cookie中获取 如果没有获取到就拦截
        String token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        if (StringUtils.isEmpty(token)){
            token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        }
        if (StringUtils.isEmpty(token)){
            // 5. 如果获取到了，那么还需要解析令牌，如果解析不成功，那么还是需要拦截返回
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie!=null){
                token = cookie.getValue();
            }
        }

        if(StringUtils.isEmpty(token)){//结束
            //直接返回401
            //重定向到登录的页面  1.设置重定向到的地址 2.设置http状态码的行为 303 302
            response.getHeaders().set("Location","http://localhost:9001/oauth/login?url="+request.getURI().toString());//url
            response.setStatusCode(HttpStatus.SEE_OTHER);
            return response.setComplete();
        }

        request.mutate().header(AUTHORIZE_TOKEN,"bearer "+token);

        return chain.filter(exchange); // 放行
    }

    @Override
    // 数据值越低，过滤器的执行的优先级越高
    public int getOrder() {
        return 0;
    }
}
